package linkExcel.utils;

import cn.hutool.core.util.StrUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelUtils {
    /**
     * 打开了Excel;或者创建空Excel和初始化sheet
     *
     * @param filePath  文件地址+Excel名称
     * @param sheetName 工作簿名称
     * @return Workbook对象
     */
    public static Workbook createOrGetExcel(String filePath, String sheetName) {
        //若未传sheet,则默认"sheet"
        if (StrUtil.isBlank(sheetName)) {
            sheetName = "sheet";
        }
        File file = new File(filePath);
        Workbook workbook = null;
        if (!file.exists()) {
            workbook = new XSSFWorkbook();
            workbook.createSheet(sheetName);
            saveExcel(workbook, filePath);
            System.out.println("文件不存在，已创建；并创建Sheet【" + sheetName + "】");
        } else {
            try (FileInputStream fis = new FileInputStream(file)) {
                workbook = new XSSFWorkbook(fis);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return workbook;
    }

    /**
     * 创建或打开Excel中的Sheet
     * @param workbook workbook
     * @param sheetName 工作簿名称
     * @return Sheet
     */
    public static Sheet createOrGetSheet(Workbook workbook, String sheetName) {
        //若未传sheet,则异常
        if (StrUtil.isBlank(sheetName)) {
            throw new RuntimeException("'工作簿名称'值为["+sheetName+"]，该参数不可为空");
        }
        Sheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) {
            sheet = workbook.createSheet(sheetName);
            System.err.println("工作簿【" + sheetName + "】不存在，已创建");
        }
        return sheet;
    }

    public static void saveExcel(Workbook workbook, String path) {
        // 保存Excel文件
        try (FileOutputStream outputStream = new FileOutputStream(path)) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除Excel
     * @param excelPath excel文件地址
     */
    public static void delExcel(String excelPath) {
        try {
            File file = new File(excelPath);
            if (!file.exists()){
                System.out.println("文件不存在！");
                return;
            }
            if(file.delete()){
                System.out.println("文件已成功删除！");
            }else{
                System.out.println("文件删除失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
